package com.wlq.demo.uitls;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.encryption.AccessPermission;
import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException;
import org.apache.pdfbox.pdmodel.encryption.StandardProtectionPolicy;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState;
import org.apache.pdfbox.text.TextPosition;
import org.apache.pdfbox.util.Matrix;
import org.apache.poi.xwpf.usermodel.UnderlinePatterns;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.springframework.core.io.ClassPathResource;

import java.io.*;

/**
 * @author csb
 * @description: TODO
 * @date 2023/11/20 17:05
 */
public class PdfUtil {

    public static void two (String in) throws IOException {
        // 加载PDF文件
        PDDocument document = PDDocument.load(new File(in));

        // 创建访问权限对象
        AccessPermission accessPermission = new AccessPermission();
        accessPermission.setCanPrint(true);
        accessPermission.setCanModify(false);
        accessPermission.setCanFillInForm(false);
        accessPermission.setCanExtractContent(false);

        // 创建保护策略对象
        StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy("password", "123456", accessPermission);

        // 应用保护策略到文档
        document.protect(protectionPolicy);

        PDType0Font font = PDType0Font.load(document, new File("D:\\test\\pdf\\11.ttf"));

        // 加水印 遍历每一页
        for (PDPage page : document.getPages()) {
            // 创建内容流以在页面上绘制文本
            PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);

            // 设置字体、颜色和透明度
            contentStream.setFont(font, 36);
            contentStream.setNonStrokingColor(200, 200, 200); // 灰色
            contentStream.setLineWidth(5);

            // 计算水印位置（居中）
            float x = page.getMediaBox().getWidth() / 2;
            float y = page.getMediaBox().getHeight() / 2;

            // 添加水印文本
            contentStream.beginText();
            contentStream.newLineAtOffset(x, y);
            contentStream.showText("水印");
            contentStream.endText();

            // 关闭内容流并保存更改
            contentStream.close();
        }

        // 保存加密后的PDF文件
        document.save("D:\\test\\pdf\\22.pdf");

        // 关闭文档
        document.close();
    }

    public static void WatermarkPDF(String in) throws IOException {
        // 加载PDF文档
        PDDocument document = PDDocument.load(new File(in));

//        PDType0Font font = PDType0Font.load(document, new File("D:\\test\\pdf\\11.ttf"));
        PDType0Font font = PDType0Font.load(document, new ClassPathResource("/static/MC.ttf").getInputStream());
//        PDType1Font font = PDType1Font.HELVETICA_BOLD;
//        PDImageXObject image = PDImageXObject.createFromFile("D:\\test\\2\\logo.png", document);
        PDImageXObject image = PDImageXObject.createFromFileByExtension(new ClassPathResource("/static/logo.png").getFile(), document);

        float pageHeight = 0;
        float pageWidth = 0;
        float margin = 40;

        // 遍历每一页
        for (PDPage page : document.getPages()) {
            // 计算水印位置（居中）
            pageHeight = page.getMediaBox().getHeight();
            pageWidth = page.getMediaBox().getWidth();

            // 创建内容流以在页面上绘制文本
            PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);

            // 设置字体、颜色和透明度
            contentStream.setFont(font, 18);
            contentStream.setNonStrokingColor(153, 153, 153); // 灰色
            contentStream.setLineWidth(5);
            // 设置水印透明度
            PDExtendedGraphicsState extendedGraphicsState = new PDExtendedGraphicsState();
            extendedGraphicsState.setNonStrokingAlphaConstant(0.8f);
            contentStream.setGraphicsStateParameters(extendedGraphicsState);

            // 添加水印文本
            contentStream.beginText();
            for (int h = 10; h < pageHeight; h = h + 250) {
                for (int w = -10; w < pageWidth; w = w + 200) {
                    contentStream.setTextMatrix(Matrix.getRotateInstance(0.7, w, h));
                    contentStream.showText("5555奶饼@163.com");
                }
            }
            contentStream.endText();
            contentStream.restoreGraphicsState();
            // 关闭内容流并保存更改
            contentStream.close();

            //添加页眉
            // 计算图片位置
            float imageWidth = image.getWidth() / 2;
            float imageHeight = image.getHeight() / 2;
            float x = margin + 20;
            float y = page.getMediaBox().getHeight() - imageHeight - margin;
            contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, true);
            contentStream.drawImage(image, x, y, imageWidth, imageHeight);
            contentStream.close();

            // 添加页脚
            contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.PREPEND, true);
            contentStream.setFont(font, 12);
            contentStream.setNonStrokingColor(51, 0, 0); // 灰色
            contentStream.beginText();
            contentStream.moveTextPositionByAmount(pageWidth - 350, margin);
            contentStream.drawString("STEM标准译文商城：https://client.mt.sunther.com/mall");
            contentStream.endText();
            contentStream.close();

        }

        // 保存带有水印的PDF文档
        document.save("D:\\test\\2\\GB16.pdf");

        // 关闭文档
        document.close();
    }

    public static void SetPdfPassword (String in){
        try {
            // 加载PDF文件
            PDDocument document = PDDocument.load(new File(in));

            // 创建访问权限对象
            AccessPermission accessPermission = new AccessPermission();
            accessPermission.setCanPrint(true);
            accessPermission.setCanModify(false);
            accessPermission.setCanFillInForm(false);
            accessPermission.setCanExtractContent(false);

            // 创建保护策略对象
            StandardProtectionPolicy protectionPolicy = new StandardProtectionPolicy("password", "123456", accessPermission);

            // 应用保护策略到文档
            document.protect(protectionPolicy);

//            // 保存加密后的PDF文件
            document.save("D:\\test\\pdf\\2.pdf");

            // 关闭文档
            document.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 截取PDF前五页
     */
    public static void getPdfSs (String in){
        try (PDDocument document = PDDocument.load(new File(in))) {
            if (document.getNumberOfPages() > 5) {
                // 截取前五页
                for (int i = document.getNumberOfPages() - 1; i >= document.getNumberOfPages() - 5; i--) {
                    PDPage page = document.getPage(i);
                    document.removePage(i);
                    if (i < 5){
                        document.addPage(page);
                    }
                }
            }

            // 保存修改后的文档
            document.save("E:\\test\\2\\GB456.pdf");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
